package com.imooc.juc.bean;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date:2021/11/5/21:27
 * @Description:这个资源类对应 ProcomsumerLockDemo 类操作，主要用 Lock 代替 synchronized 来锁定 this 对象
 */
public class SaleTicketLock {

    private int number=0;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();  // 2021/11/5 用来唤醒线程

    public void increment()  {
        lock.lock();
        try{
            //1 判断
            while (number !=0){
                condition.await();
            }

            //2 干活
            ++number;
            System.out.println(Thread.currentThread().getName() +  "\t"+number);

            //3 唤醒
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
          lock.unlock();
        }

    }


    public void decrement()  {
        lock.lock();
        try{
            //1 判断
            while (number ==0){
                condition.await();
            }

            //2 干活
            --number;
            System.out.println(Thread.currentThread().getName() +  "\t"+number);

            //3 唤醒
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }


}
